package com.lanou.wuyou.one.guide;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by dllo on 17/3/6.
 */

public class ImageLoader {
    private static final int MSG_IMG_OK = 101;
    private Handler handler;

    //构造方法
    public ImageLoader(){
        //在Handler里面更新UI
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //判断口令是否正确
                if (msg.what == MSG_IMG_OK){

                    //给imageInfo赋值
                    ImageInfo imageInfo = (ImageInfo) msg.obj;
                    //拿到imageInfo中的bitmap
                    Bitmap bitmap = imageInfo.getBitmap();
                    //拿到imageInfo中的imageView
                    ImageView imageView = imageInfo.getImageView();
                    //把bitmap放进ImageView
                    imageView.setImageBitmap(bitmap);
                }
                return false;
            }
        });
    }
    public void getImg(String url,ImageView imageView) {
        new ImgThread(url, imageView).start();
    }
        class ImgThread extends Thread {
            private String url;
            private ImageView imageView;
        public ImgThread(String url, ImageView imageView) {
            this.url = url;
            this.imageView = imageView;
        }

            @Override
            public void run() {
                //这个用来请求网址
                HttpURLConnection httpURLConnection = null;
                //这个类似于传输管道
                InputStream inputStream = null;

                try{
                    //初始化图片的URL
                    URL imgUrl = new URL(url);
                    //给url设置
                    httpURLConnection = (HttpURLConnection) imgUrl.openConnection();
                    //把http和inputStream绑定
                    inputStream = httpURLConnection.getInputStream();
                    //给图片设置输入流
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    //得到图片
                    Message message = handler.obtainMessage();
                    message.what = MSG_IMG_OK;
                    ImageInfo imageInfo = new ImageInfo(bitmap,imageView);
                    message.obj = imageInfo;
                    handler.sendMessage(message);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    //关流
                }finally {
                    if (httpURLConnection != null){
                        httpURLConnection.disconnect();
                    }
                }
            }
        }
}
